<?php
class sms_model_dkpdata extends Model {

		public function __construct(){
		parent::__construct();
				$this->dkp = 'dkp_subscribe';
				$this->cancel_dkp = 'dkp_cancel_subscribe';
		}
		
		//判断是否绑定和订阅此条数据
		public function hasSubscribe($uid , $roleid , $dkpid , $bind )
		{
			if ($roleid) {
				$result = $this->checkSubscribeState($uid, $roleid, $dkpid);
				if ($result) {
					if ($result['bind'] == 0 && $bind == 1) {
							 $this->updateBindState($uid, $roleid, $dkpid);
							return $data = 1 ;
					}else {
							return $data = 2 ;
					}					
				} else {
					return $data = 0 ;
				}
			}
		}
		
		//查询某个用户 对某条dkp数据的订阅
		public function checkSubscribeState($uid, $roleid, $dkpid)
		{
			$sql	= " select * from " . $this->dkp . " where `sub_uid` = $uid  and `sub_roleid` = $roleid  and `sub_dkpid` = $dkpid ";			
			return $this->db->fetchRow($sql);

		}
		
		//更新绑定状态
		public function updateBindState($uid, $roleid, $dkpid)
		{
			if ($uid && $roleid && $dkpid) {
					$sql	= " update " . $this->dkp . " set sub_bind = 1 where `sub_uid` = $uid  and `sub_roleid` = $roleid  and `sub_dkpid` = $dkpid ";
					return	$this->db->query($sql);
			}
		}
		
		//判断一个用户的订阅数
		public function isMaxSubscribe($uid)
		{
			$sql	= " select count(*) as num from " . $this->dkp . " where `sub_bind` = 0 and  `sub_uid` = $uid " ;
			$result = $this->db->fetchRow($sql);
			if ($result['num'] < 10) return true ;
			else return false ;
		}
		
		//添加一条订阅
		public function addSubscribe($arguments)
		{
			
			$arguments = filter_params($arguments, 
						'sub_uid', 'sub_roleid', 'sub_rolename', 'sub_dkpid', 'sub_dkpname',
						'sub_point' ,'sub_gid' ,'sub_gname' ,'sub_profession' , 'sub_bind' ,'sub_time' , 'sub_uptime');
			$arguments['sub_readed']	=	1 ;
			$arguments['sub_time']		=  time() ;
			$arguments['sub_uptime']	=  time() ;
			return $this->db->insert($this->dkp, $arguments);
			
		}
		
		//取消订阅
		public function cancelSubscribe($uid, $subid)
		{
			$sql = " select * from  " . $this->dkp . " where subid = $subid ";
			$data = $this->db->fetchRow($sql);
			if ($data && $data['sub_uid'] == $uid) {
				$sql = " delete from " . $this->dkp . " where subid = $subid " ;
				$this->db->query($sql);
				
				$url = "http://dkp235.178.com/api/clear_subscribe_cache.php";
				$post['sub_uid'] = $uid ; $post['sub_dkpid'] = $data['sub_dkpid'] ;
				$this->httpRequest($url, $post, 'post');
				
				if($data['sub_bind'] == 1) $type = 0;
				else $type = 1 ;
				
				$array = array('uid' => $uid,  'res_id' => $data['sub_roleid'] , 'type' => $type , 'dateline' => time() );
				return $this->db->insert($this->cancel_dkp, $array);		
		   }		
		}
		
		//更新dkp
		public function updateDkpData($data)
		{
			$num = count($data);

			$arr_uid = array();
			for ($i=0; $i<$num ; $i++)
			{
				$sql_uid = ' select `sub_uid`   from ' . $this->dkp . ' where sub_roleid = ' . $data[$i]['roleid'] . ' and  sub_dkpid =  ' . $data[$i]['dkpid'] . ' and  sub_readed = 1';

				$result_uid  = $this->db->fetchAll($sql_uid);
				if($result_uid) {
						$arr_uid = array_merge($arr_uid ,$result_uid);
				}				
				$sql = ' select `sub_uid`, `sub_point`  from ' . $this->dkp . ' where sub_roleid = ' . $data[$i]['roleid'] . ' and  sub_dkpid =  ' . $data[$i]['dkpid'] ;
				$result  = $this->db->fetchAll($sql);				
				if ($result) { 
					$sql_update = " update "  . $this->dkp . " set sub_point = " . $data[$i]['point'] . " , sub_readed = 0 , `sub_uptime` = " .time(). " , `sub_last_point` = " . $result[0]['sub_point'] . " where sub_roleid = " . $data[$i]['roleid'] . " and  sub_dkpid =  " . $data[$i]['dkpid'] ;
					$this->db->query($sql_update);
				}
			}		
			
			foreach($arr_uid as $v) {
					$arr[] = $v['sub_uid'];
			}

			$num = count($arr);
			$k = 1; $m = 0;
			$array = array();
			for ($i=0;$i<$num;$i++){
				if($arr[$i]) {
					for($j=$i+1;$j<$num;$j++){
						if($arr[$i] == $arr[$j]){
							 $k++;  unset($arr[$j]);
						}
					}
					if($k == 1)		$array['str_uid'][] = $arr[$i];
					else {
						$array['arr'][$m]['uid'] = $arr[$i];
						$array['arr'][$m]['num'] = $k;
						$m++;
					}
					$k = 1 ;
				}
			}
//			$array['str_uid'] = substr($array['str_uid'],0,-1) ;
			return $array;
		}
		
		//取得订阅列表
		public function getDkpListUid($uid)
		{	
			$sql	= " select * from " . $this->dkp . " where sub_uid = $uid  order by sub_uptime desc " ;
			$data	= $this->db->fetchAll($sql);	
			$array	= array();
			$m = 0 ;
			$k = 0 ;
			$w = 0 ;
			$num = count($data); 	
			$url = "http://dkp235.178.com/api/sns_get_members_info.php";
			$key_id = 112;
			$key = md5($key_id.'178dkp_sns');
			$para['dkp'] = json_encode(array('key_id'=>$key_id,'key'=>$key,'data'=>$data));
			$rst = $this->httpRequest($url,$para,'post');			
			$rst = json_decode($rst,true);		
			$data = $rst ;

			if ($num) {
				for ($i=0;$i<$num ;$i++ ) {
					if ($data[$i]) {	$yj = 0 ;
						for($j=$i+1; $j<$num ; $j++) {							
							if ($data[$i]['sub_rolename'] == $data[$j]['sub_rolename']){
								if ($data[$i]['sub_bind'] == $data[$j]['sub_bind'] && $data[$i]['sub_bind'] == 1) {
									if(!$yj) { $array['bind'][$i][] = $data[$i] ; $yj++; }
											   $array['bind'][$i][] = $data[$j];
									
									 $k ++ ;

								} elseif ($data[$i]['sub_bind'] == $data[$j]['sub_bind'] && $data[$i]['sub_bind'] == 0) { 
									 if(!$yj) { $array['order'][$i][] = $data[$i]; $yj++; }
									 			$array['order'][$i][] = $data[$j];
									 	
									$w ++ ;
								}
								 unset($data[$j]);	$m++;								
							}
						} 
						if ($m == 0) {
							if ($data[$i]['sub_bind'] == 1) {
									 $array['bind'][$i][] = $data[$i];  $k ++ ;
								} else {
									 $array['order'][$i][] = $data[$i]; $w ++ ;
								}
						}
						$m = 0 ; 
				
					}
				}
				//更新未读状态
				$sql =  " update " . $this->dkp . " set sub_readed = 1 where sub_uid = " . $uid ;
				$this->db->query($sql);
			}			

			return $array;
		}
		
		//key验证
		public function checkKeyUid($key_id, $key)
		{
			$str = '178dkp_sns';
			$checkkey = md5($key_id . $str);
			if ($key == $checkkey ) return true ;
			else return false ;
		}
		
		public function httpRequest($url, $params=array(), $method='post', $timeout=200, $headers=array()){
		$options = array(
			CURLOPT_RETURNTRANSFER => true,         // return web page
			CURLOPT_HEADER         => false,        // don't return headers
			CURLOPT_FOLLOWLOCATION => true,         // follow redirects
			CURLOPT_ENCODING       => "",           // handle all encodings
			CURLOPT_USERAGENT      => "",     // who am i
			CURLOPT_AUTOREFERER    => true,         // set referer on redirect
			CURLOPT_CONNECTTIMEOUT => 5,          // timeout on connect
			CURLOPT_TIMEOUT        => $timeout,          // timeout on response
			CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
			CURLOPT_POST           => $method=='post',            // i am sending post data
			CURLOPT_POSTFIELDS     => $params,    // this are my post vars
			CURLOPT_VERBOSE        => 1,                //
			CURLOPT_HTTPHEADER	   => $headers
		);

		$ch      = curl_init($url);
		curl_setopt_array($ch,$options);
		$content = curl_exec($ch);
		$err     = curl_errno($ch);
		$errmsg  = curl_error($ch) ;
		$header  = curl_getinfo($ch);
		curl_close($ch);
	
		return $content;
	}
	
	//删除整个dkp数据
	public function deleteDkp($dkpid)
	{
		 $sql_log = "INSERT INTO dkp_cancel_subscribe SELECT NULL, sub_uid, sub_dkpid, 11, unix_timestamp() FROM dkp_subscribe 
						WHERE  `sub_dkpid` = $dkpid";
		$this->db->query($sql_log);
		$sql = "DELETE FROM `dkp_subscribe` WHERE `sub_dkpid` = $dkpid";	
		$this->db->query($sql);
	}
	
		//删除一个dkp角色数据
	public function deleteRole($roleid , $dkpid)
	{  
		$sql_log = "INSERT INTO dkp_cancel_subscribe SELECT NULL, sub_uid, sub_dkpid, 10, unix_timestamp() FROM dkp_subscribe 
					WHERE `sub_roleid` = $roleid and  `sub_dkpid` = $dkpid";
		$this->db->query($sql_log);
		$sql = "DELETE FROM `dkp_subscribe` WHERE `sub_roleid` = $roleid and  `sub_dkpid` = $dkpid";
		$this->db->query($sql);
	}
	
	//检查订阅状态接口 dkp
	public function checkstatenew($uid ,$dkpid)
	{
		$sql = "select sub_roleid, sub_bind from dkp_subscribe where sub_uid = $uid and sub_dkpid = $dkpid " ;
		return $this->db->fetchALL($sql);
	}
}